<template>
  <div class="search-page">
    <div class="search-container">
      <div class="search-content">
        <!-- 搜索栏 -->
        <div class="search-bar-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索照片..."
            class="search-input"
            @keyup.enter="handleSearch"
            clearable
          >
            <template #append>
              <el-button @click="handleSearch" :loading="searchStore.loading">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          
          <!-- 高级搜索切换 -->
          <el-button 
            type="text" 
            @click="showAdvancedSearch = !showAdvancedSearch"
            class="advanced-search-toggle"
          >
            高级搜索
            <el-icon class="ml-1">
              <ArrowDown v-if="!showAdvancedSearch" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>
        
        <!-- 高级搜索选项 -->
        <div v-if="showAdvancedSearch" class="advanced-search">
          <el-card shadow="never">
            <div class="search-filters">
              <div class="filter-group">
                <label>日期范围：</label>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </div>
              
              <div class="filter-group">
                <label>相机品牌：</label>
                <el-select v-model="selectedCameraMake" placeholder="选择品牌" clearable>
                  <el-option
                    v-for="make in searchStore.cameraMakes"
                    :key="make.value"
                    :label="make.label"
                    :value="make.value"
                  />
                </el-select>
              </div>
              
              <div class="filter-group">
                <label>相机型号：</label>
                <el-select v-model="selectedCameraModel" placeholder="选择型号" clearable>
                  <el-option
                    v-for="model in searchStore.cameraModels"
                    :key="model.value"
                    :label="model.label"
                    :value="model.value"
                  />
                </el-select>
              </div>
              
              <div class="filter-group">
                <label>标签：</label>
                <el-select v-model="selectedTags" multiple placeholder="选择标签" clearable>
                  <el-option
                    v-for="tag in searchStore.popularTags"
                    :key="tag.id"
                    :label="tag.name"
                    :value="tag.id"
                  />
                </el-select>
              </div>
              
              <div class="filter-actions">
                <el-button type="primary" @click="applyFilters">应用筛选</el-button>
                <el-button @click="resetFilters">重置</el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 搜索建议 -->
        <div v-if="querySuggestions.length > 0 && !searchResults.length" class="search-suggestions">
          <div class="suggestions-title">搜索建议</div>
          <div class="suggestions-list">
            <el-tag
              v-for="suggestion in querySuggestions"
              :key="suggestion"
              @click="applySuggestion(suggestion)"
              class="suggestion-tag"
            >
              {{ suggestion }}
            </el-tag>
          </div>
        </div>
        
        <!-- 搜索结果 -->
        <div v-if="searchResults.length > 0" class="search-results">
          <div class="results-header">
            <h3>搜索结果 ({{ searchStore.total }})</h3>
            <div class="view-options">
              <el-button-group>
                <el-button 
                  :type="appStore.photoViewMode === 'grid' ? 'primary' : ''"
                  @click="appStore.setPhotoViewMode('grid')"
                  size="small"
                >
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button 
                  :type="appStore.photoViewMode === 'list' ? 'primary' : ''"
                  @click="appStore.setPhotoViewMode('list')"
                  size="small"
                >
                  <el-icon><List /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>
          
          <PhotoView :photos="searchResults" />
        </div>
        
        <!-- 无结果提示 -->
        <div v-else-if="hasSearched && !searchStore.loading" class="no-results">
          <el-empty description="未找到匹配的照片" />
        </div>
        
        <!-- 热门标签 -->
        <div v-if="!hasSearched" class="popular-tags">
          <h3>热门标签</h3>
          <div class="tags-cloud">
            <el-tag
              v-for="tag in searchStore.popularTags"
              :key="tag.id"
              :color="tag.color"
              @click="searchByTag(tag)"
              class="popular-tag"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../stores/app'
import { useSearchStore } from '../stores/search'
import { usePhotoStore } from '../stores/photo'
import PhotoView from '../components/photo/PhotoView.vue'
import { Search, ArrowDown, ArrowUp, Grid, List } from '@element-plus/icons-vue'

// 导入全局类型
import '../types/global'

const router = useRouter()
const appStore = useAppStore()
const searchStore = useSearchStore()
const photoStore = usePhotoStore()

// 搜索相关状态
const searchQuery = ref('')
const hasSearched = ref(false)
const showAdvancedSearch = ref(false)

// 高级搜索选项
const dateRange = ref<[string, string]>(['', ''])
const selectedCameraMake = ref('')
const selectedCameraModel = ref('')
const selectedTags = ref<number[]>([])

// 计算属性
const searchResults = computed(() => searchStore.results)
const searchSuggestions = computed(() => searchStore.suggestions)
const querySuggestions = computed(() => searchStore.suggestions.query || [])

// 生命周期钩子
onMounted(async () => {
  // 设置当前页面
  appStore.setCurrentPage('search')
  
  // 加载热门标签和相机信息
  await Promise.all([
    searchStore.fetchPopularTags(),
    searchStore.fetchCameraMakes(),
    searchStore.fetchCameraModels()
  ])
})

// 监听搜索查询变化，获取搜索建议
watch(searchQuery, async (newQuery) => {
  if (newQuery.trim().length > 0) {
    await searchStore.getSuggestions('query', newQuery)
  } else {
    searchStore.suggestions = {
      query: [],
      camera_make: [],
      camera_model: [],
      tags: [],
      albums: []
    }
  }
})

// 搜索处理
const handleSearch = async () => {
  if (!searchQuery.value.trim()) return
  
  hasSearched.value = true
  
  // 执行搜索
  await searchStore.search({
    query: searchQuery.value,
    page: 1,
    limit: searchStore.pageSize
  })
}

// 应用搜索建议
const applySuggestion = (suggestion: string) => {
  searchQuery.value = suggestion
  handleSearch()
}

// 按标签搜索
const searchByTag = async (tag: { id: number; name: string }) => {
  searchQuery.value = `#${tag.name}`
  hasSearched.value = true
  
  await searchStore.search({
    query: searchQuery.value,
    page: 1,
    limit: searchStore.pageSize,
    filters: {
      tags: [tag.id]
    }
  })
}

// 应用筛选条件
const applyFilters = async () => {
  hasSearched.value = true
  
  const filters: any = {}
  
  if (dateRange.value[0] && dateRange.value[1]) {
    filters.dateRange = {
      start: dateRange.value[0],
      end: dateRange.value[1]
    }
  }
  
  if (selectedCameraMake.value) {
    filters.cameraMake = selectedCameraMake.value
  }
  
  if (selectedCameraModel.value) {
    filters.cameraModel = selectedCameraModel.value
  }
  
  if (selectedTags.value.length > 0) {
    filters.tags = selectedTags.value
  }
  
  await searchStore.search({
    query: searchQuery.value,
    page: 1,
    limit: searchStore.pageSize,
    filters
  })
}

// 重置筛选条件
const resetFilters = () => {
  dateRange.value = ['', '']
  selectedCameraMake.value = ''
  selectedCameraModel.value = ''
  selectedTags.value = []
}

// 分页处理
const handlePageChange = async (page: number) => {
  await searchStore.search({
    query: searchQuery.value,
    page,
    limit: searchStore.pageSize
  })
}
</script>

<style scoped>
.search-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.search-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color-page);
}

/* 搜索栏样式 */
.search-bar-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.search-input {
  max-width: 600px;
}

.advanced-search-toggle {
  color: var(--el-color-primary);
}

/* 高级搜索样式 */
.advanced-search {
  margin-bottom: 20px;
}

.search-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.filter-group label {
  font-weight: 500;
  white-space: nowrap;
}

.filter-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

/* 搜索建议样式 */
.search-suggestions {
  margin-bottom: 20px;
}

.suggestions-title {
  font-weight: 500;
  margin-bottom: 10px;
  color: var(--el-text-color-regular);
}

.suggestions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-tag {
  cursor: pointer;
}

/* 搜索结果样式 */
.search-results {
  margin-bottom: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.results-header h3 {
  margin: 0;
  font-size: 18px;
}

/* 无结果样式 */
.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 热门标签样式 */
.popular-tags {
  margin-top: 40px;
}

.popular-tags h3 {
  margin-bottom: 16px;
  font-size: 18px;
}

.tags-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.popular-tag {
  cursor: pointer;
  transition: transform 0.2s;
}

.popular-tag:hover {
  transform: scale(1.05);
}
</style>